<template>
    <Card style="width:100%" class="detail-content-layout mb16">
        <template #title>
            {{ $t('采购申请') }}
        </template>
        <template #extra>
            <div class="h-arrow-wrap" @click="toggle = !toggle">
                <i :class="{toggleActive:toggle}" class="iconfont zy-common-jiantou h-arrow-icon"></i>
            </div>
        </template>
        <transition name="slide-up">
            <div v-if="toggle">
                <Form ref="form" :model="form" :rules="rules" label-position="top">
                    <Row :gutter="24">
                        <Col span="6">
                            <FormItem :label="$t('采购申请单号')" prop="prNo">
                                <Input maxlength="100" :disabled="disabled" clearable type="text" v-model="form.prNo"
                                       :placeholder="$t('请输入')"></Input>
                            </FormItem>
                        </Col>
                        <Col span="6">
                            <FormItem :label="$t('备注')">
                                <Input maxlength="200" :disabled="disabled" clearable type="text" v-model="form.remark"
                                       :placeholder="$t('请输入')"></Input>
                            </FormItem>
                        </Col>
                        <Col span="6">
                            <FormItem :label="$t('提交人')" v-if="disabled">
                                <Input disabled clearable type="text" v-model="form.submitByStr"
                                       :placeholder="$t('请输入')"></Input>
                            </FormItem>
                        </Col>
                        <Col span="6">
                            <FormItem :label="$t('提交时间')" v-if="disabled">
                                <Input disabled clearable type="text" v-model="form.submitTime"
                                       :placeholder="$t('请输入')"></Input>
                            </FormItem>
                        </Col>
                        <Col span="6" class="autoHeight">
                            <FormItem :label="$t('采购申请单号在SAP的截图')" prop="prs">
                                <uploadFile accept=".jpg,.jpeg,.png,.gif,bmp" key="33" :fileList="prs"
                                            :disabled="disabled"
                                            @change="(list)=>{form.prs = JSON.parse(JSON.stringify(list))}"/>
                            </FormItem>
                        </Col>
                    </Row>
                    <div class="tableContent">
                        <FormItem :label="$t('资产列表')+' ('+$t('只有软件类项目不需要填写设备列表。')+')'" prop="dataSource">
                            <Button v-if="!disabled" class="ivu-btn-lg" type="primary" @click="addColumns">{{
                                    $t('添加')
                                }}
                            </Button>
                            <Table class="resizable-table" border @on-column-width-resize="(a,b,c,d)=>{onColumnWidthResize(a,b,c,d,'capexPr')}" ellipsis
                                   ref="selection" :columns="columns" :data="dataSource">
                                <template slot-scope="{ row, index }" slot="action">
                  <span class="operationBtn" @click="editItem(row)"><i class="iconfont zy-common-bianji"></i>
                   {{ $t('编辑') }}
                  </span>
                                    <span class="operationBtn" @click="deleteItem(row,index)"><i
                                        class="iconfont zy-common-shanchu"></i>{{ $t('删除') }}</span>
                                </template>
                                <template slot-scope="{ row,index }" slot="quantity">
                                    <Input maxlength="10" v-if="!disabled" :disabled="disabled" clearable type="text"
                                           v-model.number="dataSource[index].quantity"
                                           :placeholder="$t('请输入')"></Input>
                                    <p style="text-align:center" v-else>{{ dataSource[index].quantity }}</p>
                                </template>
                            </Table>
                        </FormItem>
                    </div>
                </Form>
                <rejectInfo :rejectFlows="rejectFlows"/>
            </div>
        </transition>
    </Card>
</template>

<script>
import uploadFile from "@/views/devBasic/capex/components/uploadFile";
import mixins from "@/views/devBasic/capex/components/mixins";
import rejectInfo from "@/views/devBasic/capex/components/rejectInfo";

export default {
    name: "pr",
    components: {uploadFile, rejectInfo},
    mixins: [mixins],
    props: {
        info: {
            type: Object,
            default: () => {
            }
        },
        disabled: {
            type: Boolean,
            default: false
        },
        approvalInfo: {
            type: Object,
            default: () => {
            }
        },
        rejectFlows: {
            type: Object,
            default: () => {
            }
        },
    },
    data() {
        const validatePrs = (rule, value, callback) => {
            if (!(Array.isArray(this.form.prs) && this.form.prs.length > 0)) {
                callback(new Error(this.$t('请上传附件')));
            } else {
                callback();
            }
        };
        const validateDataSource = (rule, value, callback) => {
            if (!(Array.isArray(this.dataSource) && this.dataSource.length > 0) && !this.disabled) {
                callback(new Error(this.$t('请新增设备')));
            } else {
                callback();
            }
        };
        return {
            toggle: true,
            form: {
                prNo: ""
            },
            dataSource: [],
            columns: [
                {
                    title: this.$t("流水号"),
                    align: 'center',
                    tooltip: true,
                    key: "deviceMId",
                    resizable: true
                },
                {
                    title: this.$t("设备名称"),
                    align: 'center',
                    tooltip: true,
                    key: "deviceName",
                    resizable: true
                },
                {
                    title: this.$t("数量"),
                    align: 'center',
                    key: "quantity",
                    slot: "quantity",
                    resizable: true,tooltip: true,
                    renderHeader: (h) => {
                        return h('div', [
                            h('span', {
                                domProps: {
                                    innerHTML: this.$t('数量')
                                },
                                attrs: {
                                    class: "required "
                                }
                            }),
                        ])
                    }
                }
            ],
            delIds: [],
            prs: [],
            rules: {
                prs: [{required: true, validator: validatePrs, trigger: 'blur'}],
                prNo: [{required: true, message: this.$t('请输入'), trigger: 'blur'}],
                // dataSource:  [{ required:true, validator: validateDataSource, trigger: 'blur'}]
            }
        }
    },
    created() {
        // this.form.submitByStr = this.userName
        this.getColumnWidth(this.columns,'capexPr')
        this.form.prNo = this.info.prNo
        if (Array.isArray(this.info.prs) && this.info.prs.length > 0) {
            // this.prs =
            this.setParams()

        }

        // return;
        if (this.disabled) {
            // this.setParams()
            this.toggle = false
        } else if (this.rejectFlows && this.rejectFlows.approvalRemark) {
            // this.setParams()
            this.toggle = true
        } else {
            this.columns.push({
                title: this.$t('操作'),
                slot: "action",
                width: 200,
                align: "center"
            })
            this.getVisiChangeFunc()
        }
    },
    methods: {
        getVisiChangeFunc() {
            const obj = JSON.parse(window.localStorage.getItem('pr') || '{}')
            const {delIds = [], dataSource = [], prNo = "", remark = "", prs = []} = obj;
            if (Object.keys(obj).length > 0) {
                this.prs = prs
                // this.info.prs = prs;
                this.form.prs = prs
                this.form.prNo = prNo || this.info.prNo
                this.form.remark = remark
                this.delIds = delIds || []
                this.dataSource = dataSource || []
                window.localStorage.removeItem('pr')
                this.getDeviceList()
            }
        },
        setParams() {
            const {submitTime, submitRemark, submitByStr} = this.approvalInfo
            const {prs, prNo, deviceDtos} = this.info;
            this.form = Object.assign(this.form, {
                remark: submitRemark,
                submitTime,
                submitByStr,
                prs,
                prNo
            })
            this.dataSource = deviceDtos || []
            this.prs = JSON.parse(JSON.stringify(prs))

            // console.log(prs)
            // debugger
            this.$forceUpdate()
        },
        cacheForm() {
            const params = {
                ...this.form,
                dataSource: this.dataSource,
                delIds: this.delIds
            }
            window.localStorage.setItem('pr', JSON.stringify(params))
        },
        addColumns() {
            this.cacheForm()
            this.$router.push({
                path: "/devBasic/equipmentsLedgerManagement/ledgerDetailModal",
                query: {
                    status: "add",
                    capexId: this.info.id
                }
            })
        },
        async getParams(status) {
            const valid = status ? status:await this.$refs.form.validate()
            if (valid) {
                return {
                    ...this.form,
                    deviceDtos: this.dataSource
                }
            }
        },
        getDeviceList() {
            this.axios({
                method: 'get',
                url: '/dms/capex/findCapexDevice',
                params: {
                    capexId: this.info.id
                }
            }).then(res => {
                if (res.code === 200) {
                    let list = res.data;
                    for (let i = 0; i < list.length; i++) {
                        if (!this.dataSource.find(item => item.id === list[i].id) && !this.delIds.includes(list[i].id)) {
                            this.dataSource.push(list[i])
                        }
                    }
                } else {
                    this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
                }
            })
        },
        deleteItem(row, index) {
            this.delIds.push(row.id)
            this.dataSource.splice(index, 1)
        },
        editItem(row) {
            this.$router.push({
                path: "/devBasic/equipmentsLedgerManagement/ledgerDetailModal",
                query: {
                    status: "edit",
                    id: row.deviceId,
                    deviceMId: row.deviceMId,
                    assetsNo: row.assetsNo,
                }
            })
            this.cacheForm()
        }
    }
}
</script>

<style scoped lang="scss">
@import "./style";

.detail-content-layout {
    //position: relative;
}

.tableContent {
    width: 75%;
    //position: absolute;
    //top: 10px;
    position: relative;
    //top: -100px;
    padding-bottom: 25px;

    .ivu-btn-lg {
        position: absolute;
        bottom: -50px;
        right: 0;
    }
}
</style>

